(function($){

var baseEvn = {},
	$loading = $('#loading'),
	$body = $('body'),
	$head = $('#head'),
	$main = $('#main'),
	$pop = $('#pop'),
	$foot = $('#foot'),
	$countdown = $('#countdown');

	$win = $(window),
	_winHeight = $win.height(),
	_winStop = $win.scrollTop(),

	$scrollIn = $main.find('.scrollIn'),
	_scrollInNum = 0,
	_scrollInTotal = $scrollIn.length,

	popCloseNum = 0,
	isOpenHb = true,
	isHbruning = false,
	_countdownTime = null,
	_mapTop = 0,
	isMapAn = false,
	_barTop = 0,
	isBarAn = false;

function init(){
	/*$win.scrollTop(0);

	$win.on('load', function(){
		$loading.delay(300).fadeOut(function(){
			// 弹出提示
			setTimeout(function(){
				// popOpen('.pop-main-init');
			},1500);

			$countdown.addClass('slide-active');
		});

		// 加载视频
		loadVideo();

	}).on('resize', function(){
		_winStop = $win.scrollTop();
		_winHeight = $win.height();
	}).on('scroll', function(){
		_winStop = $win.scrollTop();

		scrollFadeIn();
	});*/

	// baseEvn.singlePage();

	baseEvn.fullPage();

	// 切换视频
	$main.on('click', '.video-list a', function(){
		var _html = '<iframe height="100%" width="100%" src="'+ $(this).attr('data-url') +'" frameborder="0" allowfullscreen></iframe>';

		$main.find('.video .video-box').html(_html);
	});


	// 弹出框
	$pop.on('mousewheel', function(event) {
		return false;
	});

	// 打开弹出框
	$body.on('click', '.js-pop-open', function(event) {
		var popId = $(this).attr('data-rel');
		popOpen('.' + popId);
	});

	// 打开弹出框
	$pop.on('click', '.js-pop-close', function() {
		$pop.fadeOut();

		// if(popCloseNum < 3 && !isHbruning){
		// 	popCloseNum++;
		// 	isOpenHb = true;
		// 	isHbruning = true;

		// 	// 开始10秒倒计时
		// 	countdownEvn(10);
		// }
	});

	// 弹出框-老车主答题
	$pop.on('change', '.pop-main-wd input', function() {
		var isT = $(this).prop('checked');

		if(isT){
			$(this).parent().addClass('active').siblings().removeClass('active');
		}
	});

	// 点击红包
	$pop.on('click', '.pop-main-hby img', function(){
		isOpenHb = false;

		popOpen('.pop-main-hashb');
	});

	// 我是老车主-提交领红包
	$pop.on('click', '.pop-main-wd .pop-btn', function(){
		var $form = $(this).parents('form'),
			tempArr = [];

		$form.find('input').each(function(){
			if($(this).prop('checked')){
				tempArr.push($(this).val());
			}			
		});

		var jqxhr = $.ajax({
			url: 'http://cars.fxauto.com.cn/lingzhi/api/index.php?contents=' + tempArr.join('|'),
			dataType: 'jsonp',
			method: 'get',
			async: false
		});

		jqxhr.done(function ( result ) {
			if(result.errcode == 1){
				alert(result.msg)
			}else{
				popOpen('.pop-main-whb');
			}
		}).fail(function ( result ) {
		}).always(function ( result ) {
		});
		
	});

	// 预约试驾-立即预约
	$body.on('click', '.pop-main-yysj .pop-btn,.slide2 form .btn', function(){
		var $form = $(this).parents('form');

        var parmes = {

			advertiser_id: 5,
			seriesName: $form.find('input[name="carType"]:checked').attr('data-name'),
			seriesCode: $form.find('input[name="carType"]:checked').val(),
			name: $form.find('input[name="username"]').val(),
			mobile: $form.find('input[name="mobile"]').val(),
			sex: $form.find('input[name="sex"]:checked').val(),
			email: '',

			campaignName: '菱智帮，有前途',
			campaignCode: 'lingzhi2016_003',
			terminal: 'PC',

			dealerName: $form.find('select[name="dealers"]').val(),
			dealerCode: $form.find('select[name="dealers"]').val(),
			provinceid: $form.find('select[name="provinces"]').val(),
			province: $form.find('select[name="provinces"] option:selected').text(),
			cityid: $form.find('select[name="city"]').val(),
			city: $form.find('select[name="city"] option:selected').text(),
			mediaName:getURLParam('media')?getURLParam('media'):"菱智官网"
        };

        console.log(parmes);
	    if(!parmes.dealerName){
			alert("请选择经销商！");
			return false;
		}

        var jqxhr = $.ajax({
			url: 'http://event.mediav.cn/autodata/driver_api/add',
			dataType: 'jsonp',
			method: 'post',
			async: false,
			data: parmes
		});

		jqxhr.done(function ( result ) {
			if(result.success){
				popOpen('.pop-main-yycg');
				$form.find('input').val('');
			}else{
				alert(result.msg);
			}
		}).fail(function ( result ) {
		}).always(function ( result ) {
		});

		
	});

	$('#yuyueBtn').on('click', 'a', function(){
		$('html,body').stop().animate({
			scrollTop: $main.find('.slide2').offset().top
		}, function(){
			$main.find('.slide2').addClass('slide-active').siblings().removeClass('slide-active');
		});
	});

	// creatHb($pop.find('.pop-main-hby'));

	// 经销商
	dealersEvn.shopInfo($main.find('.slide2 form'));

	// 经销商
	// dealersEvn.shopInfo($pop.find('.pop-main-yysj form'));
};

function loadVideo(){
	setTimeout(function(){
		$main.find('.video iframe').attr('src', $main.find('.video iframe').attr('data-src'));
	},1500);
};


// 地图数字跳动
function numJump(){

	setTimeout(function(){
		$main.find('.slide3').addClass('slide-active');
	},1000);
	

	$main.delay(300).find('.slide3 .map2').animate({
		height: '100%',
	},{
		duration: 800,
		complete: function(){
			numAn($main.find('.slide3 .num'));
		}
	});
};


// 数字跳动动画
function numAn(obj){
	obj.animate({
		zIndex: obj.attr('data-num')
	},{
		duration: ~~obj.attr('data-dt') || 1500,
		step: function(now, fx) {
			$(this).find('span').text(Math.ceil(now));
		}
	});
};

// numJump();

// 柱状图
function barAn(){
	$main.find('.bar-box .bar').each(function(i){
		var $span = $(this).find('span'),
			num = $span.attr('data-num');

		$(this).find('span').delay((i + 1)*300).animate({
			zIndex: num
		},{
			duration: 1000,
			step: function(now, fx) {
				$(this).css('width', Math.ceil(now) + '%').text(Math.ceil(now) + '%');
			}
		});
	});
};

// barAn();



// 跟随鼠标滚动淡入
function scrollFadeIn(){

	if(_scrollInNum < _scrollInTotal){
		$scrollIn.each(function(){
			if(($(this).offset().top - _winHeight*0.4) < _winStop){
				$(this).addClass('an-in-active');
			}
		});
	}


	// 地图数字
	if(!isMapAn && $main.find('.slide3 .map1').hasClass('an-in-active')){
		isMapAn = true;
		numJump();
	}

	// 柱状图动画
	if(!isBarAn && $main.find('.timeline .line-box .item2').hasClass('an-in-active')){
		isBarAn = true;
		barAn();
	}

	$main.find('.timeline .line-txt').each(function(){
		if($(this).hasClass('an-in-active')){
			numAn($(this));
		}
	});
	
};


// 弹出框显示
function popOpen(pClass){
	$pop.find(pClass).addClass('pop-main-active').siblings('.pop-main').removeClass('pop-main-active');

	$pop.fadeIn();
};


// 10秒倒计时
function countdownEvn(n){
	clearTimeout(_countdownTime);

	--n;
	$countdown.find('.num span').text(n);
	$countdown.find('.guan span').height(n/10*58);

	if(n <= 0){
		// 倒计时结束-红包雨
		$pop.find('.pop-main-hby').html('');
		popOpen('.pop-main-hby');
		creatHb($pop.find('.pop-main-hby'));
		return false;
	}
	
	_countdownTime = setTimeout(function(){
		countdownEvn(n);
	},1000);
};


// 红包雨
function creatHb(box){
	var $img = $('<img src="images/icon_hongbaoyu.png" alt="">');

	$img.css({
		left: rd(10,85) + '%',
		width: rd(90,140)
	});

	box.append($img);

	$img.animate({
		top: '120%'
	},{
		duration: rd(3500,5500),
		step: function(now, fx) {
			// console.log(now);
			if(!isOpenHb){
				$(this).stop();
			}
		},
		complete: function() {
			$(this).remove();
		}
	});

	setTimeout(function(){
		if(isOpenHb){
			creatHb(box);
		}else{
			isHbruning = false;
		}
	},600);
};

// n-m范围内随机数
function rd(n,m){
    var c = m-n+1;
    return Math.floor(Math.random() * c + n);
};


// 整屏切换
baseEvn.singlePage = function(){
	if($main.attr('data-page') != 'single'){
		return false;
	}

	var $singleSlide = $main.find('.single-slide'),
		$htmlBody = $('html,body'),
		resizeTime = null,
		defaults = {
			activeIdx: 0,
			nextIdx: 1,
			scrollTopVal: 0,
			isHaveHF: false,
			isInTop: true,
			isInBottom: false,
			slideLen: $singleSlide.length,
			isSliding: false,
			isWebLoad: true
		};

	// 鼠标滚动
	$main.on('mousewheel', function(event) {
		// console.log(event.deltaX, event.deltaY, event.deltaFactor);
		isRun(event.deltaY);

		return false;
	});

	// 方向键
	$(document).on('keyup', function(e){
		var code = e.which || e.keyCode;

		if(code == 37 || code == 38){
			// 上
			isRun(1);
		}else if(code == 39 || code == 40){
			// 下
			isRun(-1);
		}
		
	});


	init();

	// 初始化页面
	function init(){
		setHeight();

		$win.on('load', function(){
			changeClass();
		}).on('resize', function(){
			setHeight();
		});

	};

	// 设定高度
//	function setHeight(){
//		clearTimeout(resizeTime);
//
//		resizeTime = setTimeout(function(){
//			$main.find('.single-slide').height($win.height());
//		},200);		
//	};

	// 判断当前活动页-输出滑动到的距离
	function isRun(y){
		if(defaults.isSliding){
			return false;
		}
		defaults.isSliding = true;

		if(y == 1){
			// 往上滚动
			$head.removeClass('head-fixed');

			// 判断是否在底部
			if(defaults.isInBottom && defaults.isHaveHF){
				defaults.isInBottom = false;
				defaults.scrollTopVal = $singleSlide.eq(defaults.activeIdx).offset().top;
			}else{
				--defaults.activeIdx;

				if(defaults.activeIdx < 0){
					defaults.isInTop = true;
					defaults.activeIdx = 0;
					defaults.scrollTopVal = 0;
				}else{
					defaults.scrollTopVal = $singleSlide.eq(defaults.activeIdx).offset().top;
				}				
			}

		}else{
			// 往下滚动
			$head.addClass('head-fixed');

			// 判断是否在页面最顶部
			if(defaults.isInTop && defaults.isHaveHF){
				defaults.isInTop = false;
				defaults.scrollTopVal = $head.height();
			}else{
				++defaults.activeIdx;

				// 判断是否在最后一屏
				if(defaults.activeIdx == defaults.slideLen){
					defaults.isInBottom = true;
					--defaults.activeIdx;
					defaults.scrollTopVal = $singleSlide.eq(defaults.activeIdx).offset().top + $foot.height();
				}else{
					defaults.scrollTopVal = $singleSlide.eq(defaults.activeIdx).offset().top;
				}
			}
		}

		// console.log($singleSlide);
		slidePage();
	};

	// 页面切换
	function slidePage(){
		$htmlBody.animate({
			scrollTop: defaults.scrollTopVal
		}, function(){
			changeClass();
			defaults.isSliding = false;
		});
	};

	// 改变当前模块class
	function changeClass(){
		$main.find('.single-slide').eq(defaults.activeIdx).addClass('slide-active').siblings().removeClass('slide-active');
	};
};

// 整屏铺满自然滚动
baseEvn.fullPage = function(){
	if($main.attr('data-page') != 'full'){
		return false;
	}


	var $singleSlide = $main.find('.single-slide'),
		$htmlBody = $('html,body'),
		resizeTime = null,
		defaults = {
			activeIdx: 0,
			nextIdx: 1,
			scrollTopVal: 0,
			isHaveHF: false,
			isInTop: true,
			isInBottom: false,
			slideLen: $singleSlide.length,
			isSliding: false,
			isWebLoad: true
		};

	// 鼠标滚动
	$singleSlide.on('mousewheel', function(event) {
		// console.log(event.deltaX, event.deltaY, event.deltaFactor);
		isRun(event.deltaY);

		return false;
	});

	// 方向键
	$(document).on('keyup', function(e){
		var code = e.which || e.keyCode;

		if(code == 37 || code == 38){
			// 上
			isRun(1);
		}else if(code == 39 || code == 40){
			// 下
			isRun(-1);
		}
		
	});

	// 判断当前活动页-输出滑动到的距离
	function isRun(y){
		if(defaults.isSliding){
			return false;
		}
		defaults.isSliding = true;

		if(y == 1){
			// 往上滚动
			--defaults.activeIdx;
		}else{
			// 往下滚动
			++defaults.activeIdx;
		}

		defaults.activeIdx = defaults.activeIdx < 0 ? 0 : defaults.activeIdx;

		if(defaults.activeIdx >= 2){
			defaults.activeIdx = 2;
			defaults.scrollTopVal = $main.find('.slide3').offset().top;
		}else{
			defaults.scrollTopVal = $singleSlide.eq(defaults.activeIdx).offset().top;
		}
		

		slidePage();
	};

	// 页面切换
	function slidePage(){
		$htmlBody.animate({
			scrollTop: defaults.scrollTopVal
		}, function(){
			changeClass();
			defaults.isSliding = false;
		});
	};


	init();

	// 初始化页面
	function init(){
		$win.on('load', function(){
			setHeight();

			setTimeout(changeClass,600);
		}).on('resize', function(){
			setHeight();
		});
	};

	// 设定高度
	function setHeight(){
		clearTimeout(resizeTime);

		resizeTime = setTimeout(function(){
			$main.find('.single-slide').height(_winHeight);
		},200);		
	};

	// 改变当前模块class
	function changeClass(){
		$main.find('.single-slide').eq(defaults.activeIdx).addClass('slide-active');
	};

};



var userInfo = {
	Ip: '',
	Token: '',
	// 预约试驾
	customerUrl: 'http://event.mediav.cn/autodata/driver_api/add',
	// 老车主问答
	chezhuUrl : 'http://cars.fxauto.com.cn/lingzhi/api/index.php?contents=',

	// 经销商XML
	//shopinfoUrl: 'http://cars.fxauto.com.cn/proxy/getxml.php?url=lingzhi/All_DealerList.xml',
	shopinfoUrl: './api/shopinfo.xml',
	// 注册
	// happyRegUrl: './api/HappyReg.php',
	// 抽奖
	// happyDrawUrl: './api/HappyDraw.php',
	// 获取当前地址信息
	adrUrl: 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js',
	// token
	getToken: function(){
		// var jqxhr = $.ajax({
		// 	url: 'http://event.mediav.com/zotye_Z700Draw/mv/gettoken',
		// 	dataType: 'jsonp',
		// 	method: 'get',
		// 	async: false
		// });

		// jqxhr.done(function ( result ) {
		// 	if(result.Token){
		// 		userInfo.Token = result.Token;
		// 		userInfo.Ip = result.Ip;
		// 	}
		// }).fail(function ( result ) {
		// }).always(function ( result ) {
		// });
	}
};


// 经销商
var dealersEvn = {
	shopInfo : function(formObj){
	    var $form = formObj;

	    // console.log(formObj);
	    $.getScript(userInfo.adrUrl,function(result){  
            // var xprovince = remote_ip_info['province'];
            // var xcity = remote_ip_info['city'];

            // console.log(remote_ip_info);
            // 初始化
	  		// dealersEvn.shopInfoAjax($form, {
			// 	PIdx: 2,
			// 	CIdx: 52
			// });
	    	dealersEvn.shopInfoAjax($form, {
				PName: remote_ip_info['province'],
				CName: remote_ip_info['city']
			});
        });

		

	    // 选择省份
	    $form.on('change','select[name="provinces"]',function(){
	        var pIdx = $(this).val();

	        dealersEvn.shopInfoAjax($form, {
				PIdx: pIdx,
				isPLoad: true
			});
	    });

	    // 选择城市
	    $form.on('change','select[name="city"]',function(){
	        var pIdx = $form.find('select[name="provinces"]').val();
	        var cIdx = $(this).val();

	        dealersEvn.shopInfoAjax($form, {
				PIdx: pIdx,
				CIdx: cIdx,
				isPLoad: true,
				isCLoad: true
			});
	    });
	},
	// 读取xml
	shopInfoAjax : function(formObj, options){
		var defaults = {
			isPLoad: false,
			isCLoad: false
		};

		var opts = $.extend(defaults, options);

		// console.log(formObj);
		if(dealersEvn.data){
			dealersEvn.shopInit(formObj, opts);
			return;
		}

	    $.ajax({
	        url : userInfo.shopinfoUrl,
	        dataType: 'xml',
	        success : function( data ) {
	        	dealersEvn.data = data;

	        	dealersEvn.shopInit(formObj, opts);
	        }
	    });
	},
	// 处理省市经销商
	shopInit: function(formObj, opts){
		var provincesArr = [],
        	provinces = '',
        	provinces_name = '',
        	cityArr = [],
        	city = '',
        	city_name = '',
        	_tempFirstCityId = 0,
        	_tempCityId = '',
        	_tempCityName = '',
        	dealersArr = [];

		$(dealersEvn.data).find('list Province').each(function( key, val){
            // console.log(key, $(val).attr('name'));
            provincesArr.push('<option value="'+ $(val).attr('id')  +'">'+ $(val).attr('name') +'</option>');

            if($(val).attr('id') == opts.PIdx || $(val).attr('name') == opts.PName){
            	provinces = $(val).attr('id');
            	provinces_name = $(val).attr('name');

                $(val).find('City').each(function( key2, val2){
                	_tempCityId = $(val2).attr('id');
                	_tempCityName = $(val2).attr('name');

                	// 选择省份时，默认选第一个城市
                	if(!opts.isCLoad && key2 == 0 && !opts.CName){
                		opts.CIdx = _tempCityId;
                	}

                    cityArr.push('<option value="'+ _tempCityId +'">'+ _tempCityName +'</option>');

                    if(_tempCityId == opts.CIdx || _tempCityName == opts.CName){
                    	city = _tempCityId;
                    	city_name = _tempCityName;

                        $(val2).find('Shop').each(function( key3, val3){
                            dealersArr.push({
                            	Name: $(val3).find('Name').text(),
                            	Address: $(val3).find('Address').text(),
                            	Tel: $(val3).find('Tel').text(),
                            	Code: $(val3).find('Code').text()
                            });
                        });
                    }                      
                });
            }
        });

        // 省份
        if(!opts.isPLoad){
        	// console.log(opts.PIdx);
            formObj.find('select[name="provinces"]').html(provincesArr.join('')).find('option').each(function(index, el) {
            	if($(this).val() == provinces || $(this).text() == provinces_name){
            		$(this).prop('selected',true);
            	}
            });
        }

        // console.log(opts.isCLoad);
        
        // 城市
        if(!opts.isCLoad){
            formObj.find('select[name="city"]').html(cityArr.join(''));

            if(city != '' || city_name != ''){
            	formObj.find('select[name="city"] option').each(function(index, el) {
	            	if($(this).val() == city || $(this).text() == city_name){
	            		$(this).prop('selected',true);
	            	}
	            });
            }
        }

        // console.log(dealersArr);

        // 经销商
        if(formObj.find('select[name="dealers"]').length > 0){
        	var str = '<option value="">选择经销商</option>'

        	for (var i = 0; i < dealersArr.length; i++) {
        		str += '<option value="'+ dealersArr[i].Code +'">'+ dealersArr[i].Name +'</option>'
        	};

        	formObj.find('select[name="dealers"]').html(str);
        }
	}
};





$(function(){
	init();
});

})(jQuery);



function getParams(){
    var param = window.location.search.substring(1);
    var collect = param.split('&');
    var args = {};
    for(var i = 0, len = collect.length; i < len; i++){
        var list = collect[i].split('=');
        args[list[0]] = list[1];
    }
    
    return args;
}

var params = getParams();
for(var key in params){
    if(key == 'media'){
        setCookie(key, params[key]);
    }
}

function setCookie(name, value){
    var times = new Date();
    times.setTime(times.getTime() + 60*60*1000); 
    document.cookie = name + '=' + escape(value) + ';expires=' + times.toGMTString();
}

function getCookie(name){
    var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    var arr;
	var media = '';
    if(arr = document.cookie.match(reg)){
        media =  decodeURIComponent(unescape(arr[2]));
    }
    
    return convertCN(media);
}

function deleteCookie(name){
    var times = new Date();
    times.setTime(times.getTime() - 1);
    var value = getCookie(name);
    if(value != null && value != ''){
        document.cookie = name + '=' + value +';expires=' + times.toGMTString();
    }
}

function convertCN(name){
	var media;
	
	switch(name){
		case 'toutiao':
			media = '今日头条';
			break;
		case 'sina':
			media = '新浪';
			break;
		case 'tencent':
			media = '腾讯';
			break;
		case 'telecom':
			media = '电信弹窗';
			break;
		case 'bitauto':
			media = '易车网';
			break;
		case 'baidu':
			media = '百度';
			break;
		default:
			media = '官网';
			break;
	}
	
	return media;
	
}

var getURLParam = function(a){var i="";var e=window.location.href;var j=false;var f=a+"=";var c=f.length;if(e.indexOf("?")>-1){var g=e.substr(e.indexOf("?")+1);var d=g.split("&");for(var b=0;b<d.length;b++){if(d[b].substr(0,c)==f){var h=d[b].split("=");i=h[1];if(i.indexOf("#")>-1){var h=i.split("#");i=h[0]}j=true;break}}}if(j==false){return null}return i}